/* 
 * StikiWeb Wiki - a Wiki for Hierarchical Organizations
 * $Id: HrefServlet.java,v 1.3 2006/07/20 21:15:39 biglee Exp $
 * 
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the StikiWeb Wiki 
 *
 * The Initial Developer of the Original Code is Lee Haslup (biglee@haslups.com).
 * Portions created by the Initial Developer are Copyright (C) 2004
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** 
 */
/*
 * Created on Aug 29, 2004
 * by Allen L (BigLee) Haslup
 *
 *stikiweb - HrefServlet.java
 */
package org.stikiweb.struts;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.stikiweb.contentMagnager.Base62;

/**
 * @author biglee
 *
 * HrefServlet
 * 
 * This servlet is called when an HTML page attachment contains items with relative addresses.
 * The first identifier in the pathInfo() will be the  Base62 encoded name of the HTML page 
 * (with the final xxx.html omitted)  This is used to determine the actual name of the relatively-
 * addressed attachment and the request is forwarded to viewAttachment() to serve it.
 * 
 * This is needed because the normal processing of the content-base header information does not
 * preserve the needed (query string) information needed to identify the attachment to which 
 * relatively-addressed items are related.
 */
public class HrefServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4924673016866267939L;

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// path info will be /prefix/relPath where prefix is the Base62 encoded attachment name for the
		// attachment containing the relative-addressed link and relPath is the relative address of the
		// desired attachment.  (This new Base62().decode(prefix)+relPath is the actual name of the 
		// relatively-addressed attachemnt).
		String path = req.getPathInfo().substring(1);
		int sloc = path.indexOf('/');
		boolean returnToWiki = path.toUpperCase().endsWith("RETURN2WIKI");
		if(!returnToWiki && sloc>=0) {
			try {
				String pagePath = Base62.decode(path.substring(0,sloc));
				path = path.substring(sloc);
				int dotloc = path.lastIndexOf('.');
				String ext = "";
				if(dotloc >0) {
					ext=path.substring(dotloc+1);
				}
				// for HTML pages send a redirect to the browser (to make them bookmarkable).
				if(ext.toUpperCase().startsWith("HTM")) {
					// compute the correct URL for the BASE tag.
					String serverName = req.getServerName();
					int serverPort = req.getServerPort();
					String serverPortSt = ":"+serverPort;
					if(serverPort==80)serverPortSt="";
					String requestURI = req.getRequestURI();
					sloc = requestURI.indexOf("/href/");
					String uriPrefix = "";
					if(sloc>0) uriPrefix = requestURI.substring(0,sloc);
					String newUrl = "http://"+serverName+serverPortSt+uriPrefix+"/viewAttachment.do?name="+pagePath+path;
					resp.sendRedirect(newUrl);
				}
				// for non-HTML pages, just forward to the correct attachment.
				else {
					String newUrl = "/viewAttachment.do?name="+pagePath+path;
					getServletContext().getRequestDispatcher(newUrl).forward(req,resp);
				}
			} catch (Exception e) {
				e.printStackTrace();
				resp.setContentType("text/html");
				resp.getWriter().print("Error in Reference in HTML attachment.\n");
			}
		}
		// if path ends with RETURN2WIKI (link to exit) or
		// path doesn't make sense (possibly because of ..)
		// return to the wiki page that launched us.
		else {
			String pageName = (String)req.getSession().getAttribute("currentPage");
			if(pageName==null)pageName="Main";
			String theUrl = req.getRequestURL().toString();
			int hloc = theUrl.indexOf("/href/");
			theUrl = theUrl.substring(0,hloc);
			String newUrl = theUrl+"/viewPage.do?name=" + pageName;
			resp.sendRedirect(newUrl);
		}
	}
}
